<script setup>
import { reactive } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { emitpostwords, LogoutApi } from "@/api";
import { userPiniaStore } from "@/stores";
const router = useRouter();
const userPinia = userPiniaStore();
const putPasswordForm = reactive({
  newPassword: "",
  confirmPassword: "",
  password: "",
  username: userPinia.user.username,
});
const newPasswordRule = () => {
  if (putPasswordForm.confirmPassword !== putPasswordForm.newPassword) {
    ElMessage({
      message: "两次密码不一致",
      type: "error",
    });
  }
};

const emitpasword = async () => {
  if (putPasswordForm.password == userPinia.user.password) {
    const res = await emitpostwords(putPasswordForm);
    if (res.data.code == 0) {
      ElMessage({
        message: "修改密码成功",
        type: "success",
      });
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      router.replace("/");
    }
  } else {
    ElMessage({
      message: "原密码错误",
      type: "error",
    });
  }
};

const logout = async () => {
  // const res = await LogoutApi();
  // if (res.data.code === 0) {
  localStorage.removeItem("token");
  localStorage.removeItem("user");
  userPinia.user = {};
  //   ElMessage({
  //     message: "退出成功",
  //     type: "success",
  //   });
  router.replace("/");
  // }
};
</script>

<template>
  <div class="person-setting-page">
    <div class="content">
      <h3>修改密码</h3>
      <el-form :model="putPasswordForm">
        <el-form-item label="原密码：" :label-width="'90px'">
          <el-input v-model="putPasswordForm.password" type="password" show-password/>
        </el-form-item>
        <el-form-item label="新密码：" :label-width="'90px'">
          <el-input v-model="putPasswordForm.newPassword" type="password" show-password/>
        </el-form-item>
        <el-form-item label="确认密码：" :label-width="'90px'">
          <el-input v-model="putPasswordForm.confirmPassword" type="password" show-password @blur="newPasswordRule"/>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="emitpasword">确定</el-button>
    </div>
    <el-button class="logout-button" type="danger" @click="logout">退出登陆</el-button>
  </div>
</template>

<style lang="scss" scoped>
.person-setting-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .content {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    h3 {
      font-size: 20px;
      font-weight: 700;
      margin-bottom: 20px;
    }

    .el-form {
      width: 300px;

      .el-form-item {
        margin-bottom: 20px;
      }
    }

    .el-button {
      width: 100px;
    }
  }

  .logout-button {
    margin-top: 50px;
  }
}
</style>
